求细胞数量

题目 求细胞数量

image-3a692166

思路分析

上题的简化

这次洪水填充的方向只有四个

代码实现

#include<bits/stdc++.h>

using namespace std;

const int N=110;

char g[N][N];

bool st[N][N];

int res;

int n,m;

int dx[4]={-1,0,1,0};

int dy[4]={0,1,0,-1};

bool isVaild(int x,int y){

	return x>=0 && x<=n-1 && y>=0 && y<=m-1 && !st[x][y];

}

void dfs(int x,int y){

	for(int i=0;i<4;i++){

		int nx=x+dx[i],ny=y+dy[i];

		if(isVaild(nx,ny) && g[nx][ny]!='0'){

			st[nx][ny]=true;

			dfs(nx,ny);

			//只能用一次 不能回溯

		}

	}

}

int main()

{

	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);

	cin>>n>>m;

	for(int i=0;i<n;i++)

		cin>>g[i];

	for(int i=0;i<n;i++){

		for(int j=0;j<m;j++){

			if(g[i][j]!='0' && !st[i][j]){

				st[i][j]=true;

				dfs(i,j);

				res++;

			}

		}

	}

	cout<<res<<endl;

	return 0;

 }

同类题型

视频讲解


⬅️ 残垣断壁 🏠 00-刷题理模型 ➡️ 4、飞机降落